package com.usermanage.controller;

import com.usermanage.ExceptionConfig.MyException;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.CompanyService;
import com.usermanage.beanParam.*;
import com.usermanage.util.ErrMessageUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;

/**
 * 组织管理成员，管理基本权限，管理组织列表
 */
@Slf4j
@RestController
@RequestMapping("/company")
public class CompanyController {
    @Resource
    private CompanyService companyService;


    /**
     * 企业首页
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/list.page",method= RequestMethod.GET)
    public ModelAndView list()throws Exception{
        ModelAndView mv = new ModelAndView();
        //获得用户登陆信息
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //从用户登陆信息中获取用户权限列表
        List<PermissionBean> permissionBeanList = userDetail.getList();
        //判断用户具有的权限在界面展示
        List<PermissionBean> result = new ArrayList<>();
        for (PermissionBean bean:permissionBeanList) {
            if (bean.getPermission_url().equals("/company/add.page")){
                result.add(bean);
            }
            if (bean.getPermission_url().equals("/company/export.json")){
                result.add(bean);
            }
        }
        mv.addObject("permissionList",result);
        mv.setViewName("/company/list");
        return mv;
    }

    /**
     * 分页得到企业数据
     * @param key
     * @param page
     * @param size
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/list.json",method= RequestMethod.POST)
    public JsonData roleListJson(String key, String page, String size)throws Exception{
        if (StringUtils.isBlank(page)){
            page = StaticUtil.pageIndex;
        }
        if (StringUtils.isBlank(size)){
            size = StaticUtil.sizeCount;
        }
        //得到企业的列表
        List<CompanyBean> list =companyService.findAllList(key,page,size);
//        //根据用记录数
        int count = companyService.getAllUserListCount(key);
//        //从用户信息中获取权限列表，此处拼接列表的权限button按钮
        List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
        List<Map> operaButton = new ArrayList<>();
        for (PermissionBean bean:permissionBeanList) {
            if (bean.getPermission_url().equals("/company/cancel.json")){
                Map map = new HashMap();
                map.put("name",bean.getPermission_name());
                map.put("fn","del");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/company/update.page")){
                Map map = new HashMap();
                map.put("name",bean.getPermission_name());
                map.put("fn","modify");
                operaButton.add(map);
            }
            if (bean.getPermission_url().equals("/company/detail.page")){
                Map map = new HashMap();
                map.put("name",bean.getPermission_name());
                map.put("fn","detail");
                operaButton.add(map);
            }
        }
        if (StringUtils.isBlank(key)){
            key="''";
        }
        if (operaButton.size()==0){
            Map map = new HashMap();
            map.put("name","--");
            operaButton.add(map);
        }
        Map resultMap = new HashMap();
        resultMap.put("list",list);
        resultMap.put("total",count == 0 ? 1:count);
        resultMap.put("operaButton",operaButton);
        resultMap.put("key",key);
        resultMap.put("pageIndex",page);
        resultMap.put("size",size);
        return JsonData.success(resultMap);
    }

    /**
     * 企业添加界面
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/add.page",method= RequestMethod.GET)
    public ModelAndView add()throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/company/add");
        return mv;
    }


    @RequestMapping(value="/add.json",method= RequestMethod.POST)
    public JsonData add(@Valid CompanyBean companyBean, BindingResult bindingResult)throws Exception{
        //验证提交数据是否合法
        if(bindingResult.hasErrors()){
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        CompanyBean bean = new CompanyBean();
        bean.setCompany_name(companyBean.getCompany_name());

        boolean bool = companyService.isExisit(bean);
        if (bool){
            return JsonData.fail("该企业已被注册");
        }
//        bean.setCustom_company_name(companyBean.getCompany_name());
        companyBean.setCompany_state("11");
        companyBean.setType("11");
        return JsonData.success(companyService.save(companyBean));
    }


    /**
     * 企业详情界面
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/detail.page",method= RequestMethod.GET)
    public ModelAndView detail(String id,int type)throws Exception{
        ModelAndView mv = new ModelAndView();
        Optional<CompanyBean> optional = companyService.findById(Integer.valueOf(id));
        if (!optional.isPresent()){
            throw new MyException("系统异常");
        }
        CompanyBean bean = optional.get();
        String success = "fail";//没有修改权限
        if (1==type){//表示更新界面
            //得到登陆用户权限集合，判断用户是否有修改权限
            List<PermissionBean> permissionBeanList = SpringSecurityUtils.getCurrentUser().getList();
            for (PermissionBean permissionBean:permissionBeanList) {
                if (permissionBean.getPermission_url().equals("/company/update.json")){
                    success = "success";//有修改权限
                    break;
                }
            }
            mv.setViewName("/company/update");
        }else{//查看界面
            mv.setViewName("/company/detail");
        }
        mv.addObject("bean",bean);
        mv.addObject("success",success);
        return mv;
    }



    /**
     * 企业下拉框列表 用于超级管理员初始化合作商管理员权限
     * @return
     */
    @RequestMapping(value="/update.json",method= RequestMethod.POST)
    public JsonData updateUser(@Valid CompanyBean companyBean, BindingResult bindingResult){
        log.error("************");
        //验证提交数据是否合法
        if(bindingResult.hasErrors()){
            return JsonData.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        Optional<CompanyBean> optional = companyService.findById(companyBean.getId());
        CompanyBean bean = optional.get();
        //若企业名没有修改，直接提价，若企业名修改验证该企业名是否已经存在
        if (!bean.getCompany_name().equals(companyBean.getCompany_name())){
            CompanyBean checkBean = new CompanyBean();
            checkBean.setCompany_name(companyBean.getCompany_name());
            boolean bool = companyService.isExisit(bean);
            if (bool){
                return JsonData.fail("该企业已被注册");
            }
        }
        bean.setCompany_name(companyBean.getCompany_name());
        bean.setCompany_address(companyBean.getCompany_address());
        bean.setCompany_bankcard_name(companyBean.getCompany_bankcard_name());
        bean.setCompany_bankcard_num(companyBean.getCompany_bankcard_num());
        bean.setCompany_code(companyBean.getCompany_code());
        bean.setCompany_num(companyBean.getCompany_num());
        bean.setCompany_type(companyBean.getCompany_type());
        bean.setCompany_manage_type(companyBean.getCompany_manage_type());
        bean.setCompany_construction(companyBean.getCompany_construction());
        bean.setCompany_lastyear_sale(companyBean.getCompany_lastyear_sale());
        bean.setCompany_objective(companyBean.getCompany_objective());
        bean.setCompany_credit_code(companyBean.getCompany_credit_code());
        bean.setCompany_people_code(companyBean.getCompany_people_code());
        bean.setCompany_principal_name(companyBean.getCompany_principal_name());
        bean.setCompany_principal_position(companyBean.getCompany_principal_position());
        bean.setCompany_principal_phone(companyBean.getCompany_principal_phone());
        bean.setCompany_principal_email(companyBean.getCompany_principal_email());
        bean.setCompany_pic_url(companyBean.getCompany_pic_url());
        companyService.save(bean);

//        bean.setCompany_name(companyBean.getCompany_name());
//        boolean bool = companyService.isExisit(bean);
//        if (bool){
//            return JsonData.fail("该企业已被注册");
//        }
//        companyBean.setCompany_state("11");
        return JsonData.success();
    }

    /**
     * 用户离职
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancel.json", method = RequestMethod.POST)
    public JsonData roleListJson(int id) throws Exception {
        Optional<CompanyBean> optional = companyService.findById(id);
        if (!optional.isPresent()) {
            return JsonData.fail("企业不存在");
        }
        CompanyBean bean = optional.get();
        bean.setCompany_state("00");
        companyService.save(bean);
        return JsonData.success();
    }

    /**
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/detail.json")
    public JsonData detailJson(String id) throws Exception {
        Optional<CompanyBean> optional = companyService.findById(Integer.valueOf(id));
        if (!optional.isPresent()) {
            return JsonData.fail("企业不存在");
        }
        return JsonData.success(optional.get());
    }

    /**
     * 企业下拉框列表 用于超级管理员初始化合作商管理员权限
     * @return
     */
    @RequestMapping(value="/select.json")
    public JsonData registerUser(){
        log.error("************");
        try {
            String company_id = SpringSecurityUtils.getCurrentUser().getCompany_id();
            List<CompanyBean> list = new ArrayList<>();
            if(company_id.equals("1")){
                list= companyService.findAllForSelect();
            }else {
                list= companyService.findAllListByCompanyId(company_id);
            }
            return JsonData.success(list);
        }catch (Exception e){
            /**
             * 打印日志
             */
            return JsonData.fail(ErrMessageUtil.SysErr);
        }
    }

    //导出
    @RequestMapping(value = "/export.json")
    public void ExportExcel(HttpServletResponse response, String key) throws IOException, Exception {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("客户信息");
        //列宽
        sheet.setColumnWidth(0, 100 * 100);
        sheet.setColumnWidth(1, 100 * 100);
        sheet.setColumnWidth(2, 100 * 100);
        sheet.setColumnWidth(3, 100 * 100);
        sheet.setColumnWidth(4, 100 * 100);
        sheet.setColumnWidth(5, 100 * 100);
        sheet.setColumnWidth(6, 100 * 100);
        sheet.setColumnWidth(7, 100 * 100);
        sheet.setColumnWidth(8, 100 * 100);
        sheet.setColumnWidth(9, 100 * 100);
        sheet.setColumnWidth(10, 100 * 100);
        sheet.setColumnWidth(11, 100 * 100);
        sheet.setColumnWidth(12, 100 * 100);
        sheet.setColumnWidth(13, 100 * 100);
        sheet.setColumnWidth(14, 100 * 100);
        sheet.setColumnWidth(15, 100 * 100);
        sheet.setColumnWidth(16, 100 * 100);
        sheet.setColumnWidth(17, 100 * 100);
        sheet.setColumnWidth(18, 100 * 100);
        sheet.setColumnWidth(19, 100 * 100);
        sheet.setColumnWidth(20, 100 * 100);
        sheet.setColumnWidth(21, 100 * 100);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("公司名称");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("组织机构代码");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("营业执照注册号");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("企业性质");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("企业地址");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("经营类型");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("开发资质");
        cell.setCellStyle(style);
        cell = row.createCell(7);
        cell.setCellValue("装饰等级");
        cell.setCellStyle(style);
        cell = row.createCell(8);
        cell.setCellValue("施工资质");
        cell.setCellStyle(style);
        cell = row.createCell(9);
        cell.setCellValue("上一年度销售额");
        cell.setCellStyle(style);
        cell = row.createCell(10);
        cell.setCellValue("本年度计划销售目标");
        cell.setCellStyle(style);
        cell = row.createCell(11);
        cell.setCellValue("开户行名称");
        cell.setCellStyle(style);
        cell = row.createCell(12);
        cell.setCellValue("银行卡号");
        cell.setCellStyle(style);
        cell = row.createCell(13);
        cell.setCellValue("统一社会信用代码");
        cell.setCellStyle(style);
        cell = row.createCell(14);
        cell.setCellValue("纳税人识别号");
        cell.setCellStyle(style);
        cell = row.createCell(15);
        cell.setCellValue("纳税人名称");
        cell.setCellStyle(style);
        cell = row.createCell(16);
        cell.setCellValue("纳税人资质");
        cell.setCellStyle(style);
        cell = row.createCell(17);
        cell.setCellValue("增值税专用发票最高额（元）");
        cell.setCellStyle(style);
        cell = row.createCell(18);
        cell.setCellValue("负责人姓名");
        cell.setCellStyle(style);
        cell = row.createCell(19);
        cell.setCellValue("负责人职位");
        cell.setCellStyle(style);
        cell = row.createCell(20);
        cell.setCellValue("负责人手机号");
        cell.setCellStyle(style);
        cell = row.createCell(21);
        cell.setCellValue("负责人邮箱");
        cell.setCellStyle(style);

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        List<CompanyBean> list = companyService.findAllList(key,"0","0");

        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow((int) i + 1);

            // 第四步，创建单元格，并设置值
            row.createCell(0).setCellValue(list.get(i).getCompany_name() == null ? "" : list.get(i).getCompany_name().toString());
            row.createCell(1).setCellValue(list.get(i).getCompany_code() == null ? "" : list.get(i).getCompany_code().toString());
            row.createCell(2).setCellValue(list.get(i).getCompany_num() == null ? "" : list.get(i).getCompany_num().toString());
            row.createCell(3).setCellValue(list.get(i).getCompany_type()== null ? "" : list.get(i).getCompany_type().toString());
            row.createCell(4).setCellValue(list.get(i).getCompany_address() == null ? "" : list.get(i).getCompany_address().toString());
            row.createCell(5).setCellValue(list.get(i).getCompany_manage_type() == null ? "" : list.get(i).getCompany_manage_type().toString());
            row.createCell(6).setCellValue(list.get(i).getCompany_exploit() == null ? "" : list.get(i).getCompany_exploit().toString());
            row.createCell(7).setCellValue(list.get(i).getCompany_decoration() == null ? "" : list.get(i).getCompany_decoration().toString());
            row.createCell(8).setCellValue(list.get(i).getCompany_construction() == null ? "" : list.get(i).getCompany_construction().toString());
            row.createCell(9).setCellValue(list.get(i).getCompany_lastyear_sale());
            row.createCell(10).setCellValue(list.get(i).getCompany_objective());
            row.createCell(11).setCellValue(list.get(i).getCompany_bankcard_name() == null ? "" : list.get(i).getCompany_bankcard_name().toString());
            row.createCell(12).setCellValue(list.get(i).getCompany_bankcard_num() == null ? "" : list.get(i).getCompany_bankcard_num().toString());
            row.createCell(13).setCellValue(list.get(i).getCompany_credit_code() == null ? "" : list.get(i).getCompany_credit_code().toString());
            row.createCell(14).setCellValue(list.get(i).getCompany_people_code() == null ? "" : list.get(i).getCompany_people_code().toString());
            row.createCell(15).setCellValue(list.get(i).getCompany_people_name() == null ? "" : list.get(i).getCompany_people_name().toString());
            row.createCell(16).setCellValue(list.get(i).getCompany_people_resource() == null ? "" : list.get(i).getCompany_people_resource().toString());
            row.createCell(17).setCellValue(list.get(i).getCompany_invoice_price());
            row.createCell(18).setCellValue(list.get(i).getCompany_principal_name() == null ? "" : list.get(i).getCompany_principal_name().toString());
            row.createCell(19).setCellValue(list.get(i).getCompany_principal_position() == null ? "" : list.get(i).getCompany_principal_position().toString());
            row.createCell(20).setCellValue(list.get(i).getCompany_principal_phone() == null ? "" : list.get(i).getCompany_principal_phone().toString());
            row.createCell(21).setCellValue(list.get(i).getCompany_principal_email() == null ? "" : list.get(i).getCompany_principal_email().toString());
        }
        // 第六步，将文件存到指定位置
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-disposition", "attachment;filename=COMPANY.xls");//默认Excel名称
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            wb.close();
        }
    }


}
